package com.syuchen.server.http;

import com.syuchen.protocol.http.Response;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.Map;

public class ResponseSender {

    public static void send(Response response, OutputStream outputStream) {
        try {
            BufferedWriter responseWriter = new BufferedWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8));
            responseWriter.write(response.getVersion() + " " + response.getStatus_code() + " " + response.getStatus_description() + "\r\n");
            Map<String, String> headers = response.getHeaders();
            if (headers != null) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    responseWriter.write(entry.getKey() + ":" + entry.getValue() + "\r\n");
                }
            }
            responseWriter.write("\r\n");
            String body = response.getBody();
            if (body != null && body.length() > 0) {
                responseWriter.write(body);
            }
            responseWriter.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
